<template>
  <div class="practice-settings-page">
    <div class="settings-container">
      <!-- 简洁的标题栏 -->
      <div class="page-header">
        <div class="title-section">
          <h1 v-if="module !== 'wrongQuestions'">{{ moduleName }}模块练习</h1>
          <h1 v-else>错题本练习</h1>
        </div>
      </div>
      
      <!-- 主内容区域 -->
      <div class="main-content">
        <div class="settings-form">
          <el-form :model="practiceForm" label-width="90px" class="practice-form">
            <el-form-item :label="module === 'vocabulary-accumulation' ? '词语数量' : '题目数量'">
              <el-select v-model="practiceForm.count" :placeholder="module === 'vocabulary-accumulation' ? '选择词语数量' : '选择题目数量'">
                <el-option label="全部" :value="0"></el-option>
                <el-option :label="module === 'vocabulary-accumulation' ? '5个' : '5题'" :value="5"></el-option>
                <el-option :label="module === 'vocabulary-accumulation' ? '10个' : '10题'" :value="10"></el-option>
                <el-option :label="module === 'vocabulary-accumulation' ? '15个' : '15题'" :value="15"></el-option>
                <el-option :label="module === 'vocabulary-accumulation' ? '20个' : '20题'" :value="20"></el-option>
              </el-select>
            </el-form-item>
            
            <!-- 词汇积累模块只显示题目数量 -->
            <template v-if="module === 'vocabulary-accumulation'">
              <!-- 只显示题目数量，不显示其他选项 -->
              <el-form-item>
                <el-button type="primary" @click="startPractice" :loading="loading" class="start-button">
                  开始练习
                </el-button>
              </el-form-item>
            </template>
            
            <!-- 非词汇积累模块显示其他设置项 -->
            <template v-else>
            
            <el-form-item label="题目模块" v-if="module === 'wrongQuestions'">
              <el-select v-model="practiceForm.module" placeholder="选择题目模块">
                <el-option label="全部" value=""></el-option>
                <el-option label="时政" value="politics" />
                <el-option label="常识" value="commonSense" />
                <el-option label="言语理解" value="language" />
                <el-option label="判断" value="judgment" />
                <el-option label="数量" value="quantitative" />
                <el-option label="资料" value="dataAnalysis" />
              </el-select>
            </el-form-item>

            <el-form-item label="题目类型" v-if="module !== 'vocabulary-accumulation'">
              <el-select v-model="practiceForm.type" placeholder="选择题目类型">
                <el-option label="全部" value=""></el-option>
                <el-option label="单选题" value="single_choice"></el-option>
                <el-option label="多选题" value="multiple_choice"></el-option>
                <el-option label="判断题" value="true_false"></el-option>
                <el-option label="填空题" value="fill_blank"></el-option>
              </el-select>
            </el-form-item>
            
            <!-- 添加练习模式选择 -->
            <el-form-item label="练习模式">
              <el-radio-group v-model="practiceForm.mode">
                <el-radio label="practice">做题模式</el-radio>
                <el-radio label="drill">刷题模式</el-radio>
              </el-radio-group>
            </el-form-item>

            <!-- 申论模块添加大类别和小类别筛选 -->
            <el-form-item label="大类别" v-if="module === 'shenlun'">
              <el-select v-model="practiceForm.category" placeholder="请选择大类别" @change="handleCategoryChange">
                <el-option label="全部" value=""></el-option>
                <el-option
                  v-for="category in shenlunCategories"
                  :key="category.value"
                  :label="category.label"
                  :value="category.value">
                </el-option>
              </el-select>
            </el-form-item>
            
            <el-form-item label="小类别" v-if="module === 'shenlun'">
              <el-select v-model="practiceForm.subCategory" placeholder="请选择小类别" :disabled="!practiceForm.category">
                <el-option label="全部" value=""></el-option>
                <el-option
                  v-for="subCategory in filteredSubCategories"
                  :key="subCategory.value"
                  :label="subCategory.label"
                  :value="subCategory.value">
                </el-option>
              </el-select>
            </el-form-item>
            
            <!-- 六大题库模块添加大类别和小类别筛选 -->
            <el-form-item label="大类别" v-if="['commonSense', 'language', 'judgment', 'quantitative', 'dataAnalysis'].includes(module)">
              <el-select v-model="practiceForm.category" placeholder="请选择大类别" @change="handleCategoryChange">
                <el-option label="全部" value=""></el-option>
                <el-option
                  v-for="category in moduleCategories[module as keyof typeof moduleCategories]"
                  :key="category.value"
                  :label="category.label"
                  :value="category.value">
                </el-option>
              </el-select>
            </el-form-item>
            
            <el-form-item label="小类别" v-if="['commonSense', 'language', 'judgment', 'quantitative', 'dataAnalysis'].includes(module) && practiceForm.category">
              <el-select v-model="practiceForm.subCategory" placeholder="请选择小类别" :disabled="!practiceForm.category">
                <el-option label="全部" value=""></el-option>
                <el-option
                  v-for="subCategory in filteredSubCategoriesAll"
                  :key="subCategory.value"
                  :label="subCategory.label"
                  :value="subCategory.value">
                </el-option>
              </el-select>
            </el-form-item>
            
            <!-- 时政模块使用时间筛选 -->
            <el-form-item label="时间筛选" v-if="module === 'politics'">
              <el-date-picker
                v-model="practiceForm.category"
                type="date"
                placeholder="时间筛选"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%;"
                clearable
              />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="startPractice" :loading="loading" class="start-button">
                开始练习
              </el-button>
            </el-form-item>
          </template>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Flag, Compass, ChatDotRound, DataLine, Finished, Document, CollectionTag, Setting, Sunny } from '@element-plus/icons-vue';
import request from '@/api/request';

const props = defineProps({
  module: {
    type: String,
    required: true
  }
});

const emit = defineEmits(['start-practice']);

const router = useRouter();
const loading = ref(false);

// 模块配置
const moduleConfig = {
  politics: {
    name: '时政',
    icon: Flag,
    description: '掌握时事政治，了解国家大事',
    tips: [
      '关注时事热点，积累政治常识',
      '理解政策背景，把握发展趋势',
      '结合实际案例，加深理解'
    ],
    categories: [
      { label: '政治', value: 'Politics' },
      { label: '经济', value: 'Economics' },
      { label: '文史', value: 'HistoryLiterature' },
      { label: '科学与生活', value: 'ScienceLife' },
      { label: '地理', value: 'Geography' },
      { label: '法律', value: 'Law' },
      { label: '管理与公文', value: 'ManagementDocuments' }
    ] as { label: string; value: string }[]
  },
  commonSense: {
    name: '常识',
    icon: Compass,
    description: '拓展知识面，提升综合素养',
    tips: [
      '广泛涉猎各领域知识',
      '注重知识点之间的联系',
      '多做练习，巩固记忆'
    ],
    categories: [
      { label: '政治', value: 'Politics' },
      { label: '经济', value: 'Economics' },
      { label: '文史', value: 'HistoryLiterature' },
      { label: '科学与生活', value: 'ScienceLife' },
      { label: '地理', value: 'Geography' },
      { label: '法律', value: 'Law' },
      { label: '管理与公文', value: 'ManagementDocuments' }
    ] as { label: string; value: string }[]
  },
  language: {
    name: '言语理解',
    icon: ChatDotRound,
    description: '提升语言文字运用能力',
    tips: [
      '注重语感训练，多读多练',
      '掌握解题技巧，提高效率',
      '积累词汇，扩大知识面'
    ],
    categories: [
      { label: '片段阅读', value: 'SegRead' },
      { label: '语句表达', value: 'SenExp' },
      { label: '逻辑填空', value: 'LogFill' }
    ] as { label: string; value: string }[]
  },
  judgment: {
    name: '判断推理',
    icon: Finished,
    description: '锻炼逻辑思维，提升推理能力',
    tips: [
      '培养逻辑思维能力',
      '掌握各类题型特点',
      '多练习，提高解题速度'
    ],
    categories: [
      { label: '定义推理', value: 'DefRea' },
      { label: '类比推理', value: 'AnaRea' },
      { label: '逻辑推理', value: 'LogRea' },
      { label: '图形推理', value: 'GraRea' }
    ] as { label: string; value: string }[]
  },
  quantitative: {
    name: '数量关系',
    icon: DataLine,
    description: '提升数学运算能力',
    tips: [
      '掌握基本数学公式',
      '培养数学思维',
      '多练习计算技巧'
    ],
    categories: [
      { label: '倍数特性', value: 'MulCha' },
      { label: '方程问题', value: 'EquPro' },
      { label: '等差数列和等比数列', value: 'AriGeoSeq' },
      { label: '周期问题', value: 'PerPro' },
      { label: '工程问题', value: 'EngPro' },
      { label: '几何问题', value: 'GeoPro' },
      { label: '容斥原理问题', value: 'IncExcPro' },
      { label: '最值问题', value: 'ExtValPro' },
      { label: '年龄问题', value: 'AgePro' },
      { label: '溶液问题', value: 'SolPro' },
      { label: '植树与方程问题', value: 'PlanEquPro' },
      { label: '经济利润问题', value: 'EcoPro' },
      { label: '行程问题', value: 'TraPro' },
      { label: '排列组合问题', value: 'ComPermPro' },
      { label: '数量易拿分小题型', value: 'EasyNumPro' }
    ] as { label: string; value: string }[]
  },
  dataAnalysis: {
    name: '资料分析',
    icon: Document,
    description: '提升数据分析和处理能力',
    tips: [
      '快速定位关键信息',
      '掌握计算技巧',
      '提高阅读理解能力'
    ],
    categories: [
      { label: '八大常用速算技巧', value: 'FastCal' },
      { label: '基期量', value: 'BaseVal' },
      { label: '现期量', value: 'CurrVal' },
      { label: '增长率', value: 'GrowthRt' },
      { label: '增长量', value: 'GrowthAmt' },
      { label: '间隔增长率', value: 'IntvGrowth' },
      { label: '乘积增长率', value: 'ProdGrowth' },
      { label: '年均增长率', value: 'AnnGrowth' },
      { label: '混合增长率', value: 'MixGrowth' },
      { label: '比重', value: 'Proportion' },
      { label: '平均数', value: 'Average' },
      { label: '倍数', value: 'Multiple' },
      { label: 'A与非A思想', value: 'ANotA' },
      { label: '综合分析', value: 'CompAnaly' }
    ] as { label: string; value: string }[]
  },
  'vocabulary-accumulation': {
    name: '词汇积累',
    icon: CollectionTag,
    description: '扩大词汇量，提升语言表达能力',
    tips: [
      '每天坚持学习新词汇',
      '注重词汇的实际运用',
      '通过阅读积累词汇'
    ],
    categories: [] as { label: string; value: string }[]
  },
  wrongQuestions: {
    name: '错题',
    icon: Document,
    description: '巩固知识点，提高答题正确率',
    tips: [
      '针对性复习错题，查漏补缺',
      '分析错误原因，总结解题思路',
      '定期复习，加深记忆',
      '选择相应模块进行专项练习'
    ],
    categories: [] as { label: string; value: string }[]
  }
};

// 计算属性
const currentModule = computed(() => {
  const moduleKey = props.module as keyof typeof moduleConfig;
  return moduleConfig[moduleKey] || {};
});

const moduleName = computed(() => {
  return currentModule.value.name || '练习';
});

const moduleTips = computed(() => {
  return currentModule.value.tips || [];
});

// 申论大类别选项
const shenlunCategories = [
  { value: '概括归纳', label: '概括归纳' },
  { value: '综合分析', label: '综合分析' },
  { value: '解决问题', label: '解决问题' },
  { value: '公文写作', label: '公文写作' },
  { value: '文章写作', label: '文章写作' }
];

// 申论小类别选项
const shenlunSubCategories = [
  // 概括归纳
  { value: '概括题', label: '概括题', parent: '概括归纳' },
  { value: '归纳题', label: '归纳题', parent: '概括归纳' },
  
  // 综合分析
  { value: '词句解释', label: '词句解释', parent: '综合分析' },
  { value: '观点分析', label: '观点分析', parent: '综合分析' },
  { value: '现象分析', label: '现象分析', parent: '综合分析' },
  { value: '要素分析', label: '要素分析', parent: '综合分析' },
  { value: '比较分析', label: '比较分析', parent: '综合分析' },
  
  // 解决问题
  { value: '单一对策', label: '单一对策', parent: '解决问题' },
  { value: '复合对策', label: '复合对策', parent: '解决问题' },
  { value: '变异对策', label: '变异对策', parent: '解决问题' },
  
  // 公文写作
  { value: '普适类', label: '普适类', parent: '公文写作' },
  { value: '提纲类', label: '提纲类', parent: '公文写作' },
  { value: '要点类', label: '要点类', parent: '公文写作' },
  
  // 文章写作
  { value: '解释类', label: '解释类', parent: '文章写作' },
  { value: '分析类', label: '分析类', parent: '文章写作' },
  { value: '对策类', label: '对策类', parent: '文章写作' }
];

// 六大模块分类选项
const moduleCategories: Record<string, Array<{ value: string; label: string }>> = {
  // 时政模块分类（使用时间筛选，但保留分类选项以保持一致性）
  politics: [],
  
  // 常识模块分类
  commonSense: [
    { value: 'Politics', label: '政治' },
    { value: 'Economics', label: '经济' },
    { value: 'HistoryLiterature', label: '文史' },
    { value: 'ScienceLife', label: '科学与生活' },
    { value: 'Geography', label: '地理' },
    { value: 'Law', label: '法律' },
    { value: 'ManagementDocuments', label: '管理与公文' }
  ],
  
  // 言语模块分类
  language: [
    { value: 'SegRead', label: '片段阅读' },
    { value: 'SenExp', label: '语句表达' },
    { value: 'LogFill', label: '逻辑填空' }
  ],
  
  // 数量模块分类
  quantitative: [
    { value: 'MulCha', label: '倍数特性' },
    { value: 'EquPro', label: '方程问题' },
    { value: 'AriGeoSeq', label: '等差数列和等比数列' },
    { value: 'PerPro', label: '周期问题' },
    { value: 'EngPro', label: '工程问题' },
    { value: 'GeoPro', label: '几何问题' },
    { value: 'IncExcPro', label: '容斥原理问题' },
    { value: 'ExtValPro', label: '最值问题' },
    { value: 'AgePro', label: '年龄问题' },
    { value: 'SolPro', label: '溶液问题' },
    { value: 'PlanEquPro', label: '植树与方程问题' },
    { value: 'EcoPro', label: '经济利润问题' },
    { value: 'TraPro', label: '行程问题' },
    { value: 'ComPermPro', label: '排列组合问题' },
    { value: 'EasyNumPro', label: '数量易拿分小题型' }
  ],
  
  // 判断模块分类
  judgment: [
    { value: 'DefRea', label: '定义推理' },
    { value: 'AnaRea', label: '类比推理' },
    { value: 'LogRea', label: '逻辑推理' },
    { value: 'GraRea', label: '图形推理' }
  ],
  
  // 资料模块分类
  dataAnalysis: [
    { value: 'FastCal', label: '八大常用速算技巧' },
    { value: 'BaseVal', label: '基期量' },
    { value: 'CurrVal', label: '现期量' },
    { value: 'GrowthRt', label: '增长率' },
    { value: 'GrowthAmt', label: '增长量' },
    { value: 'IntvGrowth', label: '间隔增长率' },
    { value: 'ProdGrowth', label: '乘积增长率' },
    { value: 'AnnGrowth', label: '年均增长率' },
    { value: 'MixGrowth', label: '混合增长率' },
    { value: 'Proportion', label: '比重' },
    { value: 'Average', label: '平均数' },
    { value: 'Multiple', label: '倍数' },
    { value: 'ANotA', label: 'A与非A思想' },
    { value: 'CompAnaly', label: '综合分析' }
  ]
};

// 六大模块子类别选项
const allSubCategories: Record<string, Array<{ value: string; label: string; parent: string }>> = {
  // 常识模块子分类
  Politics: [
    { value: 'CurrentPolitics', label: '时事政治', parent: 'Politics' },
    { value: 'PolicyInterpretation', label: '政策解读', parent: 'Politics' },
    { value: 'PoliticalTheory', label: '政治理论', parent: 'Politics' }
  ],
  Economics: [
    { value: 'MacroEconomics', label: '宏观经济', parent: 'Economics' },
    { value: 'MicroEconomics', label: '微观经济', parent: 'Economics' },
    { value: 'EconomicPolicy', label: '经济政策', parent: 'Economics' }
  ],
  HistoryLiterature: [
    { value: 'ChineseHistory', label: '中国历史', parent: 'HistoryLiterature' },
    { value: 'WorldHistory', label: '世界历史', parent: 'HistoryLiterature' },
    { value: 'LiteraryKnowledge', label: '文学常识', parent: 'HistoryLiterature' }
  ],
  ScienceLife: [
    { value: 'NaturalScience', label: '自然科学', parent: 'ScienceLife' },
    { value: 'LifeCommonSense', label: '生活常识', parent: 'ScienceLife' },
    { value: 'TechnologyFrontier', label: '科技前沿', parent: 'ScienceLife' }
  ],
  Geography: [
    { value: 'PhysicalGeography', label: '自然地理', parent: 'Geography' },
    { value: 'HumanGeography', label: '人文地理', parent: 'Geography' },
    { value: 'GeographicalKnowledge', label: '地理常识', parent: 'Geography' }
  ],
  Law: [
    { value: 'ConstitutionalLaw', label: '宪法法律', parent: 'Law' },
    { value: 'AdministrativeLaw', label: '行政法', parent: 'Law' },
    { value: 'CivilLaw', label: '民法', parent: 'Law' }
  ],
  ManagementDocuments: [
    { value: 'Management', label: '管理学', parent: 'ManagementDocuments' },
    { value: 'OfficialDocumentWriting', label: '公文写作', parent: 'ManagementDocuments' },
    { value: 'AdministrativeManagement', label: '行政管理', parent: 'ManagementDocuments' }
  ],
  
  // 言语模块子分类
  SegRead: [
    { value: 'CentralComprehension', label: '中心理解题', parent: 'SegRead' },
    { value: 'DetailJudgment', label: '细节判断题', parent: 'SegRead' }
  ],
  SenExp: [
    { value: 'DiscourseSelection', label: '接语选择题', parent: 'SenExp' },
    { value: 'SentenceFilling', label: '语句填空题', parent: 'SenExp' },
    { value: 'SentenceOrdering', label: '语句排序题', parent: 'SenExp' }
  ],
  LogFill: [
    { value: 'WordAnalysis', label: '词的辨析', parent: 'LogFill' },
    { value: 'ContextualAnalysis', label: '语境分析', parent: 'LogFill' }
  ],
  
  // 数量模块子分类
  MulCha: [
    { value: 'Parity', label: '奇偶性', parent: 'MulCha' },
    { value: 'Divisibility', label: '整除特性', parent: 'MulCha' },
    { value: 'RatioMultiple', label: '比例倍数', parent: 'MulCha' }
  ],
  EquPro: [
    { value: 'LinearEquation', label: '一元一次方程', parent: 'EquPro' },
    { value: 'BinaryLinearEquation', label: '二元一次方程', parent: 'EquPro' },
    { value: 'IndeterminateEquation', label: '不定方程', parent: 'EquPro' }
  ],
  AriGeoSeq: [
    { value: 'ArithmeticSequence', label: '等差数列', parent: 'AriGeoSeq' },
    { value: 'GeometricSequence', label: '等比数列', parent: 'AriGeoSeq' }
  ],
  PerPro: [
    { value: 'CycleIdentification', label: '周期识别', parent: 'PerPro' },
    { value: 'CycleCalculation', label: '周期计算', parent: 'PerPro' }
  ],
  EngPro: [
    { value: 'WorkTimeProblem', label: '工程时间问题', parent: 'EngPro' },
    { value: 'WorkEfficiencyProblem', label: '工程效率问题', parent: 'EngPro' }
  ],
  GeoPro: [
    { value: 'PlaneGeometry', label: '平面几何', parent: 'GeoPro' },
    { value: 'SolidGeometry', label: '立体几何', parent: 'GeoPro' }
  ],
  IncExcPro: [
    { value: 'TwoSetProblem', label: '两集合问题', parent: 'IncExcPro' },
    { value: 'ThreeSetProblem', label: '三集合问题', parent: 'IncExcPro' }
  ],
  ExtValPro: [
    { value: 'MaximumProblem', label: '最大值问题', parent: 'ExtValPro' },
    { value: 'MinimumProblem', label: '最小值问题', parent: 'ExtValPro' }
  ],
  AgePro: [
    { value: 'AgeRelationship', label: '年龄关系', parent: 'AgePro' },
    { value: 'AgeCalculation', label: '年龄计算', parent: 'AgePro' }
  ],
  SolPro: [
    { value: 'SolutionConcentration', label: '溶液浓度', parent: 'SolPro' },
    { value: 'SolutionMixing', label: '溶液混合', parent: 'SolPro' }
  ],
  PlanEquPro: [
    { value: 'PlantingProblem', label: '植树问题', parent: 'PlanEquPro' },
    { value: 'EquationApplication', label: '方程应用', parent: 'PlanEquPro' }
  ],
  EcoPro: [
    { value: 'ProfitProblem', label: '利润问题', parent: 'EcoPro' },
    { value: 'InterestProblem', label: '利息问题', parent: 'EcoPro' }
  ],
  TraPro: [
    { value: 'MeetingProblem', label: '相遇问题', parent: 'TraPro' },
    { value: 'PursuitProblem', label: '追及问题', parent: 'TraPro' }
  ],
  ComPermPro: [
    { value: 'CombinationProblem', label: '组合问题', parent: 'ComPermPro' },
    { value: 'PermutationProblem', label: '排列问题', parent: 'ComPermPro' }
  ],
  EasyNumPro: [
    { value: 'SimpleCalculation', label: '简单计算', parent: 'EasyNumPro' },
    { value: 'SpecialValueMethod', label: '特殊值法', parent: 'EasyNumPro' }
  ],
  
  // 判断模块子分类
  DefRea: [
    { value: 'SingleDefinition', label: '单定义', parent: 'DefRea' },
    { value: 'MultipleDefinition', label: '多定义', parent: 'DefRea' }
  ],
  AnaRea: [
    { value: 'AttributeAnalogy', label: '属性类比', parent: 'AnaRea' },
    { value: 'StructureAnalogy', label: '结构类比', parent: 'AnaRea' }
  ],
  LogRea: [
    { value: 'TranslationReasoning', label: '翻译推理', parent: 'LogRea' },
    { value: 'LogicalCalculation', label: '逻辑计算', parent: 'LogRea' }
  ],
  GraRea: [
    { value: 'NinePalaceGrid', label: '九宫格', parent: 'GraRea' },
    { value: 'SpaceReconstruction', label: '空间重构', parent: 'GraRea' }
  ],
  
  // 资料模块子分类
  FastCal: [
    { value: 'TruncationMethod', label: '截位法', parent: 'FastCal' },
    { value: 'DirectDivision', label: '直除法', parent: 'FastCal' }
  ],
  BaseVal: [
    { value: 'BasePeriodCalculation', label: '基期计算', parent: 'BaseVal' },
    { value: 'BasePeriodComparison', label: '基期比较', parent: 'BaseVal' }
  ],
  CurrVal: [
    { value: 'CurrentPeriodCalculation', label: '现期计算', parent: 'CurrVal' },
    { value: 'CurrentPeriodComparison', label: '现期比较', parent: 'CurrVal' }
  ],
  GrowthRt: [
    { value: 'GrowthRateCalculation', label: '增长率计算', parent: 'GrowthRt' },
    { value: 'GrowthRateComparison', label: '增长率比较', parent: 'GrowthRt' }
  ],
  GrowthAmt: [
    { value: 'GrowthAmountCalculation', label: '增长量计算', parent: 'GrowthAmt' },
    { value: 'GrowthAmountComparison', label: '增长量比较', parent: 'GrowthAmt' }
  ],
  IntvGrowth: [
    { value: 'IntervalGrowthRate', label: '间隔增长率', parent: 'IntvGrowth' },
    { value: 'IntervalBasePeriod', label: '间隔基期', parent: 'IntvGrowth' }
  ],
  ProdGrowth: [
    { value: 'ProductGrowthRate', label: '乘积增长率', parent: 'ProdGrowth' },
    { value: 'ProductBasePeriod', label: '乘积基期', parent: 'ProdGrowth' }
  ],
  AnnGrowth: [
    { value: 'AnnualGrowthRate', label: '年均增长率', parent: 'AnnGrowth' },
    { value: 'AnnualAverageGrowth', label: '年均增长量', parent: 'AnnGrowth' }
  ],
  MixGrowth: [
    { value: 'MixedGrowthRate', label: '混合增长率', parent: 'MixGrowth' },
    { value: 'MixedBasePeriod', label: '混合基期', parent: 'MixGrowth' }
  ],
  Proportion: [
    { value: 'ProportionCalculation', label: '比重计算', parent: 'Proportion' },
    { value: 'ProportionComparison', label: '比重比较', parent: 'Proportion' }
  ],
  Average: [
    { value: 'AverageCalculation', label: '平均数计算', parent: 'Average' },
    { value: 'AverageComparison', label: '平均数比较', parent: 'Average' }
  ],
  Multiple: [
    { value: 'MultipleCalculation', label: '倍数计算', parent: 'Multiple' },
    { value: 'MultipleComparison', label: '倍数比较', parent: 'Multiple' }
  ],
  ANotA: [
    { value: 'ANotAConcept', label: 'A与非A概念', parent: 'ANotA' },
    { value: 'ANotAApplication', label: 'A与非A应用', parent: 'ANotA' }
  ],
  CompAnaly: [
    { value: 'ComprehensiveCalculation', label: '综合计算', parent: 'CompAnaly' },
    { value: 'ComprehensiveComparison', label: '综合比较', parent: 'CompAnaly' }
  ]
};

// 根据大类别过滤小类别选项（申论模块）
const filteredSubCategories = computed(() => {
  if (!practiceForm.category) {
    return [];
  }
  return shenlunSubCategories.filter(item => item.parent === practiceForm.category);
});

// 根据大类别过滤小类别选项（六大模块）
const filteredSubCategoriesAll = computed(() => {
  if (!practiceForm.category) {
    return [];
  }
  return allSubCategories[practiceForm.category] || [];
});

// 处理大类别变化
const handleCategoryChange = () => {
  // 清空小类别选择
  practiceForm.subCategory = '';
  
  // 特殊处理时政模块
  if (props.module === 'politics') {
    // 时政模块使用时间筛选，不使用category字段
    practiceForm.category = '';
  }
};

// 在practiceForm中添加subCategory字段
const practiceForm = reactive({
  count: 0, // 0表示全部题目
  type: '',
  questionType: '', // 新增判断题目类型
  category: '',
  subCategory: '', // 添加小类别字段
  module: '', // 添加module属性
  mode: 'practice' // 添加练习模式字段，默认为做题模式
});

const startPractice = async () => {
  loading.value = true;
  try {
    // 特殊处理错题模块：如果选择了具体模块，检查是否有题目
    if (props.module === 'wrongQuestions' && practiceForm.module) {
      // 构造检查题目数量的参数
      const checkParams: Record<string, any> = {
        module: practiceForm.module,
        count: 1  // 只需要检查是否有题目，不需要获取全部
      };
      
      // 添加其他筛选条件
      if (practiceForm.type) checkParams.questionType = practiceForm.type;
      
      try {
        // 发送请求检查是否有题目
        const checkResponse = await request.get('/api/wrong-question/practice', { params: checkParams });
        
        // 如果没有题目，直接提示并返回
        if (!checkResponse.data || checkResponse.data.length === 0) {
          ElMessage.warning('该模块下没有错题，请选择其他模块');
          loading.value = false;
          return;
        }
      } catch (checkError) {
        // 如果检查失败，回退到原来的逻辑
        console.warn('检查题目数量时出错，回退到原有逻辑:', checkError);
      }
    }
    
    // 特殊处理错题模块：如果选择了具体模块，检查是否有题目
    if (props.module === 'wrongQuestions' && practiceForm.module) {
      // 构造检查题目数量的参数
      const checkParams: Record<string, any> = {
        module: practiceForm.module,
        count: 1  // 只需要检查是否有题目，不需要获取全部
      };
      
      // 添加其他筛选条件
      if (practiceForm.type) checkParams.questionType = practiceForm.type;
      
      try {
        // 发送请求检查是否有题目
        const checkResponse = await request.get('/api/wrong-question/practice', { params: checkParams });
        
        // 如果没有题目，直接提示并返回
        if (!checkResponse.data || checkResponse.data.length === 0) {
          ElMessage.warning('该模块下没有错题，请选择其他模块');
          loading.value = false;
          return;
        }
      } catch (checkError) {
        // 如果检查失败，回退到原来的逻辑
        console.warn('检查题目数量时出错，回退到原有逻辑:', checkError);
      }
    }
    
    // 验证小分类是否有效
    if (practiceForm.category && practiceForm.subCategory) {
      let isValidSubCategory = false;
      
      // 检查申论模块
      if (props.module === 'shenlun') {
        isValidSubCategory = shenlunSubCategories.some(item => 
          item.parent === practiceForm.category && item.value === practiceForm.subCategory
        );
      } 
      // 检查六大题库模块
      else if (['politics', 'commonSense', 'language', 'judgment', 'quantitative', 'dataAnalysis'].includes(props.module)) {
        const subCategories = allSubCategories[practiceForm.category] || [];
        isValidSubCategory = subCategories.some(item => item.value === practiceForm.subCategory);
      }
      
      // 如果小分类不属于当前大分类，显示错误信息
      if (!isValidSubCategory) {
        ElMessage.error('选择的小分类与大分类不匹配，请重新选择');
        loading.value = false;
        return;
      }
    }
    
    // 获取分类和子分类的中文标签
    let categoryLabel = '';
    let subCategoryLabel = '';
    
    // 获取大分类中文标签
    if (practiceForm.category) {
      if (props.module === 'shenlun') {
        const category = shenlunCategories.find(cat => cat.value === practiceForm.category);
        categoryLabel = category ? category.label : practiceForm.category;
      } else if (['commonSense', 'language', 'judgment', 'quantitative', 'dataAnalysis'].includes(props.module)) {
        const categories = moduleCategories[props.module as keyof typeof moduleCategories] || [];
        const category = categories.find(cat => cat.value === practiceForm.category);
        categoryLabel = category ? category.label : practiceForm.category;
      }
    }
    
    // 获取小分类中文标签
    if (practiceForm.subCategory) {
      if (props.module === 'shenlun') {
        const subCategory = shenlunSubCategories.find(sub => sub.value === practiceForm.subCategory);
        subCategoryLabel = subCategory ? subCategory.label : practiceForm.subCategory;
      } else if (['commonSense', 'language', 'judgment', 'quantitative', 'dataAnalysis'].includes(props.module)) {
        const subCategories = allSubCategories[practiceForm.category] || [];
        const subCategory = subCategories.find(sub => sub.value === practiceForm.subCategory);
        subCategoryLabel = subCategory ? subCategory.label : practiceForm.subCategory;
      }
    }
    
    const params: Record<string, any> = {};
    
    // 特殊处理词汇积累模块
    if (props.module === 'vocabulary-accumulation') {
      // 对于词汇积累模块，0表示获取全部，其他正数表示获取指定数量
      if (practiceForm.count >= 0) {
        params.count = practiceForm.count;
      }
    } else {
      // 其他模块保持原有逻辑
      params.count = practiceForm.count >= 0 ? practiceForm.count : undefined; // 当count为0时也传递，表示获取全部
    }
    
    // 添加其他通用参数
    if (practiceForm.type) params.questionType = practiceForm.type;
    if (categoryLabel) params.category = categoryLabel;
    if (subCategoryLabel) params.subCategory = subCategoryLabel;
    if (practiceForm.module) params.module = practiceForm.module;
    
    // 添加排序字段（除非是词汇积累模块）
    if (props.module !== 'vocabulary-accumulation') {
      params.orderBy = 'question_id';
      params.orderType = 'asc';
    }
    
    // 特殊处理时政模块的时间筛选
    if (props.module === 'politics' && practiceForm.category) {
      params.date = practiceForm.category;
      delete params.category;
    }
    
    // 过滤掉空值
    Object.keys(params).forEach(key => {
      if (params[key] === undefined || params[key] === '') {
        delete params[key];
      }
    });
    
    console.log('发送练习参数:', params);
    
    // 发送开始练习事件
    emit('start-practice', {
      module: props.module,
      params: params,
      mode: practiceForm.mode
    });
    
  } catch (error: any) {
    console.error('开始练习失败:', error);
    ElMessage.error('开始练习失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.practice-settings-page {
  width: 100%;
  min-height: calc(100vh - 64px);
  background: #f5f7fa;
  box-sizing: border-box;
  position: relative;
  overflow: hidden;
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding: 20px;
}

.settings-container {
  width: 100%;
  max-width: 700px;
  margin: 0 auto;
  padding: 20px;
  box-sizing: border-box;
  position: relative;
  z-index: 1;
}

.page-header {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 24px;
}

.title-section {
  flex: 1;
  text-align: center;
}

.title-section h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  text-shadow: none;
  letter-spacing: 0.5px;
}

.main-content {
  width: 100%;
}

.settings-form {
  background: transparent;
  border-radius: 0;
  padding: 0;
  box-shadow: none;
  border: none;
}

.practice-form {
  max-width: 100%;
}



/* 表单项样式优化 */
:deep(.el-form-item) {
  margin-bottom: 28px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
  font-size: 14px;
}

:deep(.el-select),
:deep(.el-date-picker) {
  width: 100%;
}

:deep(.el-select .el-input__wrapper),
:deep(.el-date-picker .el-input__wrapper) {
  border-radius: 4px;
  transition: all 0.3s ease;
  background: white;
}



:deep(.el-radio-group) {
  display: flex;
  gap: 16px;
}

:deep(.el-radio) {
  margin-right: 0;
  padding: 10px 20px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: all 0.3s ease;
  font-size: 14px;
  background: white;
}

:deep(.el-radio:hover) {
  border-color: #409eff;
  background: #ecf5ff;
}

:deep(.el-radio.is-checked) {
  border-color: #409eff;
  background: #ecf5ff;
}

:deep(.el-radio__label) {
  font-weight: 400;
}

.start-button {
  width: 100%;
  height: 44px;
  border-radius: 4px;
  font-size: 16px;
  font-weight: 500;
  margin-top: 8px;
}

@media (max-width: 768px) {
  .practice-settings-page {
    padding: 16px;
  }
  
  .page-header {
    margin-bottom: 20px;
  }
  
  .title-section h1 {
    font-size: 24px;
  }
  
  .settings-form {
    padding: 32px 24px;
    border-radius: 20px;
  }
  
  :deep(.el-form-item) {
    margin-bottom: 24px;
  }
  
  :deep(.el-radio-group) {
    flex-direction: column;
    gap: 12px;
  }
  
  :deep(.el-radio) {
    width: 100%;
    justify-content: center;
  }
  
  .start-button {
    height: 52px;
    font-size: 16px;
  }
}
</style>
